#!/bin/bash

DOMAIN=$1
if [ -z $DOMAIN ]; then
    DOMAIN="testsuite.nmos.tv"
fi

# Remove old CA files
rm -rf certs
rm -rf crl
rm index.txt*
rm -rf intermediate
rm -rf newcerts
rm -rf private
rm serial*

# Create CA
mkdir certs crl newcerts private
chmod 700 private
touch index.txt
echo 1000 > serial
openssl genrsa -out private/ca.key.pem 4096
chmod 400 private/ca.key.pem
openssl req -config openssl.cnf -key private/ca.key.pem -new -x509 -days 18250 -sha256 -extensions v3_ca -out certs/ca.cert.pem -subj "/C=GB/ST=England/O=NMOS Testing Ltd/CN=ca.$DOMAIN"
chmod 444 certs/ca.cert.pem

# Create Intermediate
mkdir intermediate
cp openssl.cnf.intermediate intermediate/openssl.cnf
mkdir intermediate/certs intermediate/crl intermediate/csr intermediate/newcerts intermediate/private
touch intermediate/index.txt
echo 1000 > intermediate/serial
echo 1000 > intermediate/crlnumber
openssl genrsa -out intermediate/private/intermediate.key.pem 4096
chmod 400 intermediate/private/intermediate.key.pem
export SAN="DNS.1:ica.$DOMAIN"
export DOMAIN=$DOMAIN
openssl req -config intermediate/openssl.cnf -new -sha256 -key intermediate/private/intermediate.key.pem -out intermediate/csr/intermediate.csr.pem -subj "/C=GB/ST=England/O=NMOS Testing Ltd/CN=ica.$DOMAIN"
openssl ca -batch -config openssl.cnf -extensions v3_intermediate_ca -days 18250 -notext -md sha256 -in intermediate/csr/intermediate.csr.pem -out intermediate/certs/intermediate.cert.pem
chmod 444 intermediate/certs/intermediate.cert.pem
openssl x509 -pubkey -noout -in intermediate/certs/intermediate.cert.pem -out intermediate/certs/intermediate.pubkey.pem
chmod 444 intermediate/certs/intermediate.pubkey.pem

# Create certificate chain
cat intermediate/certs/intermediate.cert.pem certs/ca.cert.pem > intermediate/certs/ca-chain.cert.pem
chmod 444 intermediate/certs/ca-chain.cert.pem

# Create CRL
openssl ca -config intermediate/openssl.cnf -gencrl -out intermediate/crl/intermediate.crl.pem

# Create OCSP pair
openssl genrsa -out intermediate/private/ocsp.$DOMAIN.key.pem 4096
openssl req -config intermediate/openssl.cnf -new -sha256 -key intermediate/private/ocsp.$DOMAIN.key.pem -out intermediate/csr/ocsp.$DOMAIN.csr.pem -subj "/C=GB/ST=England/O=NMOS Testing Ltd/CN=ocsp.$DOMAIN"
openssl ca -batch -config intermediate/openssl.cnf -extensions ocsp -days 18250 -notext -md sha256 -in intermediate/csr/ocsp.$DOMAIN.csr.pem -out intermediate/certs/ocsp.$DOMAIN.cert.pem
